package cn.itcast.dtx.notifydemo.bank1.server.impl;

import cn.itcast.dtx.notifydemo.bank1.dao.AccountInfoDao;
import cn.itcast.dtx.notifydemo.bank1.entity.AccountPay;
import cn.itcast.dtx.notifydemo.bank1.model.AccountChangeEvent;
import cn.itcast.dtx.notifydemo.bank1.server.AccountInfoService;
import cn.itcast.dtx.notifydemo.bank1.spring.PayClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author misterWei
 * @create 2020年02月17号:13点23分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService{

    @Autowired
    private AccountInfoDao accountInfoDao;

    @Autowired
    private PayClient payClient;

    /**
     * 用来更新余额操作,必须幂等判断,应为有2个调用方
     * @param accountChange
     */
    @Transactional
    @Override
    public void updateAccountBalance(AccountChangeEvent accountChange) {
        //首先进行幂等性判断
        int existTx = accountInfoDao.isExistTx(accountChange.getTxNo());
        if (existTx > 0){
            return;
        }
        accountInfoDao.updateAccountBalance(accountChange.getAccountNo(),accountChange.getAmount());
        accountInfoDao.addTx(accountChange.getTxNo());

    }

    /**
     * 用来对外提供一个查询API,进行更新余额操作;
     * @param tx_no
     * @return
     */
    @Override
    public AccountPay queryPayResult(String tx_no) {
        //远程fegin组件
        AccountPay payresult = payClient.payresult(tx_no);
        if ("success".equals(payresult.getResult())){
            AccountChangeEvent accountChangeEvent = new AccountChangeEvent();
            accountChangeEvent.setTxNo(payresult.getId());
            accountChangeEvent.setAccountNo(payresult.getAccountNo());
            accountChangeEvent.setAmount(payresult.getPayAmount());
            updateAccountBalance(accountChangeEvent);
        }
        return payresult;
    }
}
